import { asyncRoutes, constantRoutes } from '@/router'
import { login } from '@/api/api'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routes
  }
}

const actions = {


  // login({ commit }, userInfo) {
  //   const { username, password, type } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ account: username.trim(), passWord: password, type: type }).then(response => {
  //       const { data } = response
  //       localStorage.setItem('logindata', JSON.stringify(response.data.meau));
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },


  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // let accessedRoutes = asyncRoutes || [];
      //   if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }


      
      try {
        let objList = {} ; // 缓存buttom
        JSON.parse(localStorage.getItem('logindata')).forEach((item, index) => {
          objList[item.path] = item.buttons
          item.children.forEach((item1,index1) => {
            objList[item.path + '/' + item1.path] = item1.buttons
          })
        })
        localStorage.setItem('jurisdiction', JSON.stringify(objList));
      } catch {

      }

      let accessedRoutes = JSON.parse(localStorage.getItem('logindata'))


      // commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
